package com.cx.auth.controller;

import com.cx.auth.mapper.SysRequestPathMapper;
import com.cx.auth.vo.SysPermission;
import com.cx.auth.vo.dto.SysRequestPathDTO;
import com.cx.auth.redis.RedisConstant;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.security.KeyPair;
import java.security.interfaces.RSAPublicKey;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * @author zhangcx
 * @Description TODO
 * @date 2022/6/8 14:21
 * @email zhangcx@bluemoon.com.cn
 */
@RestController
public class CommonController {

    @GetMapping("/test")
    public String test(){
        return "SUCCESS";
    }


    @GetMapping("/666")
    public String oauth(){
        return "6666";
    }

    @Autowired
    private KeyPair keyPair;

    @Autowired
    private SysRequestPathMapper sysRequestPathMapper;

    @GetMapping("/rsa/publicKey")
    public Map<String, Object> getKey() {
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAKey key = new RSAKey.Builder(publicKey).build();
        return new JWKSet(key).toJSONObject();
    }

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @PostConstruct
    public void initData() {
        List<SysRequestPathDTO> sysRequestPathDTOList = sysRequestPathMapper.finAllPathAndPermission();
        if (!CollectionUtils.isEmpty(sysRequestPathDTOList)){
            sysRequestPathDTOList.stream().forEach(data ->{
                Map<String, List<String>> resourceRolesMap = new TreeMap<>();
                List<String> permissionCodes = new ArrayList<>();
                if (!CollectionUtils.isEmpty(data.getPermissionCodeList())){
                    permissionCodes = data.getPermissionCodeList().stream().map(SysPermission::getPermissionCode).collect(Collectors.toList());
                }
                resourceRolesMap.put(data.getUrl(),permissionCodes);
                redisTemplate.opsForHash().putAll(RedisConstant.MENU_INFO.getKey(), resourceRolesMap);
            });
        }
    }

    @PostMapping("/create/code")
    public String createCode(@RequestParam("clientId")String clientId,
                             @RequestParam("phone")String phone){
        int code=(int) (Math.random()*9000+1000);
        redisTemplate.opsForValue().set(RedisConstant.SMS_CODE +"_"+ phone +"_"+ clientId +"_"+ code, String.valueOf(code));
        return String.valueOf(code);
    }

}
